<script>
import { ref, h, defineComponent, onMounted } from "vue";
import { NButton, NDivider, useMessage } from "naive-ui";
import axios from "axios";
import { cloneDeep } from "lodash";
import dayjs from "dayjs";

const createColumns = ({
  play,
  showTeam,
  showScoreDetail,
  showPerformance,
}) => {
  return [
    {
      title: "昵称",
      key: "name",
      minWidth: 100,
    },
    {
      title: "编号",
      key: "codeText",
      minWidth: 100,
    },
    {
      title: "电话",
      key: "phone",
      minWidth: 100,
    },
    {
      title: "状态",
      key: "statusText",
      minWidth: 100,
    },
    {
      title: "级别",
      key: "levelText",
      minWidth: 100,
    },
    {
      title: "积分",
      key: "score",
      minWidth: 100,

      render(row) {
        return [
          h(
            NButton,
            {
              text: true,
              tag: "a",
              type: "info",
              size: "small",
              onClick: () => showScoreDetail(cloneDeep(row)),
            },
            { default: () => row.score }
          ),
        ];
      },
    },
    {
      title: "团队成员",
      key: "team",
      minWidth: 100,
      render(row) {
        return [
          h(
            NButton,
            {
              text: true,
              tag: "a",
              type: "info",
              size: "small",
              onClick: () => showTeam(cloneDeep(row)),
            },
            { default: () => row.teamMembers }
          ),
        ];
      },
    },
    {
      title: "团队业绩",
      key: "teamPerformance",
      minWidth: 100,
      render(row) {
        return [
          h(
            NButton,
            {
              text: true,
              tag: "a",
              type: "info",
              size: "small",
              onClick: () => showPerformance(cloneDeep(row)),
            },
            { default: () => row.teamPerformance }
          ),
        ];
      },
    },
    {
      title: "操作",
      key: "actions",
      minWidth: 100,

      render(row) {
        return [
          h(
            NButton,
            {
              text: true,
              tag: "a",
              type: "info",
              size: "small",
              onClick: () => play(cloneDeep(row)),
            },
            { default: () => "编辑" }
          ),
        ];
      },
    },
  ];
};

export default defineComponent({
  setup() {
    const message = useMessage();
    const data = ref([]);
    const formRef = ref();
    const showModalRef = ref(false);
    const showTreeModalRef = ref(false);
    const showScoreModalRef = ref(false);
    const showPerformanceRef = ref(false);
    const cureentRow = ref({});
    const treeData = ref([]);
    const scoreData = ref([]);
    const PerformanceData = ref([]);

    const pagination = ref({
      page: 1,
      pageSize: 10,
      itemCount: 10,
    });
    const initQueryData = ref({
      name: null,
      phone: null,
      status: null,
      level: null,
      page: 1,
      rows: 10,
    });
    // const queryData = ref(cloneDeep(initQueryData));
    // console.log("queryData",queryData);

    const queryData = ref({
      name: "",
      phone: null,
      status: null,
      level: null,
      page: 1,
      rows: 10,
    });

    const statusOptions = [
      {
        label: "启用",
        value: 1,
      },
      {
        label: "禁用",
        value: 0,
      },
    ];
    const levelOptions = [
      {
        label: "游客",
        value: 1,
      },
      {
        label: "代理商",
        value: 2,
      },
      {
        label: "分公司",
        value: 3,
      },
    ];

    onMounted(() => {
      findList(queryData.value);
    });

    function findList(queryData) {
      console.log("列表", queryData);
      axios({
        method: "post",
        url: "/userInfo/findPage",
        data: queryData,
      }).then(function (response) {
        if (response.data.code === 200) {
          data.value = response.data.data.list;
          pagination.value.itemCount = response.data.data.totalCount;
        }
      });
    }

    function handlePageSize(currentSize) {
      pagination.value.pageSize = currentSize;
      pagination.value.page = 1;
      findList({
        page: pagination.value.page,
        rows: pagination.value.pageSize,
      });
    }
    function handlePageChange(currentPage) {
      pagination.value.page = currentPage;
      findList({
        page: pagination.value.page,
        rows: pagination.value.pageSize,
      });
    }

    function clear() {
      queryData.value = {
        name: "",
        phone: null,
        status: null,
        level: null,
        page: 1,
        rows: 10,
      };
      findList(queryData.value);
    }

    return {
      clear,
      data,
      queryData,
      treeData,
      scoreData,
      PerformanceData,
      statusOptions,
      levelOptions,
      dayjs,
      formRef,
      handlePageChange,
      handlePageSize,
      columns: createColumns({
        play(row) {
          showModalRef.value = true;
          cureentRow.value = row;
        },
        showTeam(row) {
          axios({
            method: "post",
            url: "/userInfo/findTeamMembers",
            params: { id: row.id },
          }).then(function (response) {
            if (response.data.code === 200) {
              showTreeModalRef.value = true;
              treeData.value = response.data.data;
            }
          });
        },
        showPerformance(row) {
          axios({
            method: "post",
            url: `/userInfo/findPerformanceDetail?userId=${row.id}`,
            // data: { userId: row.id },
          }).then(function (response) {
            if (response.data.code === 200 && response.data.data.length > 0) {
              showPerformanceRef.value = true;
              PerformanceData.value = response.data.data;
            }
          });
        },
        showScoreDetail(row) {
          axios({
            method: "post",
            url: `/userInfo/findScoreDetail?userId=${row.id}`,
            // data: { userId: row.id },
          }).then(function (response) {
            if (response.data.code === 200 && response.data.data.length > 0) {
              showScoreModalRef.value = true;
              scoreData.value = response.data.data;
            }
          });
        },
      }),
      pagination,
      showModal: showModalRef,
      showTreeModal: showTreeModalRef,
      showScoreModal: showScoreModalRef,
      showPerformance: showPerformanceRef,
      cureentRow,
      findList,

      save(row) {
        formRef.value.validate((errors) => {
          if (!errors) {
            showModalRef.value = false;
            axios({
              method: "post",
              url: "/userInfo/update",
              data: row,
            }).then(function (response) {
              if (response.data.code === 200) {
                message.success("保存成功");
                findList(queryData.value);
              }
            });
          }
        });
      },

      // clear() {

      //   queryData.value = cloneDeep(initQueryData);
      //   findList(queryData.value);

      // },

      rules: {
        name: {
          required: true,
          trigger: "input",
          message: "请输入昵称",
        },
        phone: {
          required: true,
          trigger: "input",
          message: "请输入电话",
        },
        score: {
          type: "number",
          required: true,
          trigger: "change",
          message: "请输入积分",
        },
      },
    };
  },
});
</script>

<template>
  <n-form inline label-placement="left" :model="queryData" class="formStyle">
    <n-form-item label="昵称" path="name">
      <n-input v-model:value="queryData.name" placeholder="输入昵称" />
    </n-form-item>
    <n-form-item label="电话" path="phone">
      <n-input v-model:value="queryData.phone" placeholder="输入电话" />
    </n-form-item>
    <n-form-item :span="12" label="状态" path="status">
      <n-select
        :clearable="true"
        v-model:value="queryData.status"
        placeholder="请选择"
        :options="statusOptions"
      />
    </n-form-item>
    <n-form-item :span="12" label="级别" path="level">
      <n-select
        :clearable="true"
        v-model:value="queryData.level"
        placeholder="请选择"
        :options="levelOptions"
      />
    </n-form-item>
    <n-form-item>
      <n-button style="margin-left: 20px" @click="clear"> 重置 </n-button>
      <n-button
        type="info"
        style="margin-left: 20px"
        @click="findList(queryData)"
      >
        查询
      </n-button>
    </n-form-item>
  </n-form>

  <n-data-table
    class="tableStyle"
    :columns="columns"
    :data="data"
    :pagination="pagination"
    :bordered="true"
    remote
    @update:page="handlePageChange"
    @update:page-size="handlePageSize"
  />

  <n-modal
    v-model:show="showModal"
    :mask-closable="false"
    preset="dialog"
    :show-icon="false"
    :closable="false"
    style="height: 480px"
  >
    <n-form
      ref="formRef"
      :rules="rules"
      :model="cureentRow"
      label-placement="left"
      label-width="auto"
      require-mark-placement="right-hanging"
      :style="{
        maxWidth: '640px',
      }"
    >
      <n-form-item label="昵称" path="name">
        <n-input v-model:value="cureentRow.name" placeholder="请输入" />
      </n-form-item>
      <n-form-item label="编码" path="code">
        <n-input
          v-model:value="cureentRow.codeText"
          placeholder="请输入"
          :disabled="true"
        />
      </n-form-item>
      <n-form-item label="电话" path="phone">
        <n-input
          v-model:value="cureentRow.phone"
          placeholder="请输入"
          :disabled="true"
        />
      </n-form-item>
      <n-form-item label="状态" path="status">
        <n-radio-group v-model:value="cureentRow.status">
          <n-space>
            <n-radio :value="1"> 启用 </n-radio>
            <n-radio :value="0"> 禁用 </n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
      <n-form-item label="级别" path="level">
        <n-radio-group v-model:value="cureentRow.level">
          <n-space>
            <n-radio :value="1"> 游客 </n-radio>
            <n-radio :value="2"> 代理商 </n-radio>
            <n-radio :value="3"> 分公司 </n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
      <n-form-item label="积分" path="score">
        <n-input-number v-model:value="cureentRow.score" placeholder="请输入" />
      </n-form-item>
      <div style="display: flex; justify-content: flex-end; margin-top: 20px">
        <n-button style="margin-right: 20px" @click="showModal = false">
          取消
        </n-button>
        <n-button type="primary" @click="save(cureentRow)"> 保存 </n-button>
      </div>
    </n-form>
  </n-modal>

  <n-modal
    v-model:show="showTreeModal"
    :mask-closable="true"
    preset="dialog"
    :show-icon="false"
    :closable="false"
    style="max-height: 600px; overflow-y: scroll"
  >
    <n-tree
      block-line
      :data="treeData"
      key-field="id"
      label-field="nameText"
      children-field="children"
      :default-expand-all="true"
      selectable
    />
  </n-modal>

  <n-modal
    v-model:show="showScoreModal"
    :mask-closable="true"
    preset="dialog"
    :show-icon="false"
    :closable="false"
    style="max-height: 600px; overflow-y: scroll"
  >
    <div class="item" v-for="i in scoreData">
      <div class="top">{{ i.month }}</div>
      <div v-for="item in i.value">
        <div style="display: flex; justify-content: space-between">
          <span>{{ item.remark }}</span
          ><span :style="{ color: item.changeScore >= 0 ? 'green' : 'red' }"
            >{{ item.changeScore >= 0 ? "+" : "" }}{{ item.changeScore }}</span
          >
        </div>
        <div
          style="
            font-size: 12px;
            margin-top: 5px;
            color: rgb(122, 122, 122);
            display: flex;
            justify-content: space-between;
          "
        >
          <span>{{ dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss") }}</span
          ><span>剩余 {{ item.afterScore }}</span>
        </div>
        <n-divider />
      </div>
    </div>
  </n-modal>

  <n-modal
    v-model:show="showPerformance"
    :mask-closable="true"
    preset="dialog"
    :show-icon="false"
    :closable="false"
    style="max-height: 600px; overflow-y: scroll"
  >
    <div v-for="item in PerformanceData">
      <div
        class="PerformanceItem"
        style="display: flex; justify-content: space-between"
      >
        <div style="display: flex; justify-content: space-between">
          <span>{{ item.month }}</span>
        </div>
        <div
          style="
            margin-top: 5px;
            color: rgb(122, 122, 122);
            display: flex;
            justify-content: space-between;
          "
        >
          <span>{{ item.value }}</span>
        </div>
      </div>

      <n-divider />
    </div>
  </n-modal>
</template>

<style>
.tableStyle {
  margin-left: 20px;
  width: 94%;
}

.formStyle {
  margin: 40px 0px 0px 30px;
}

.n-form.n-form--inline .n-form-item {
  width: 100%;
  margin-right: 18px;
}

.top {
  padding: 10px 0;
  background-color: #f1f3f4;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
